package com.xjc.common;

import cn.hutool.core.util.StrUtil;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.CommentEntity;
import org.flowable.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.task.Comment;
import org.flowable.engine.task.Event;

/**
 * <p>
 * 审批意见
 * </p>
 *
 * @author xiaojincai
 * @since 2025-07-17
 */
@Getter
@ToString
@EqualsAndHashCode(callSuper = false)
public class HisCommentCmd implements Command<Comment> {

    /**
     * 流程实例id
     */
    private final String procInstId;
    /**
     * 任务id
     */
    private final String taskId;
    /**
     * 用户
     */
    private final String user;

    /**
     * 类型
     */
    private final String type;

    /**
     * 意见信息
     */
    private final String message;

    public HisCommentCmd(String procInstId, String taskId, String user, String type, String message) {
        this.procInstId = procInstId;
        this.taskId = taskId;
        this.user = user;
        this.type = type;
        this.message = message;
    }

    @Override
    public Comment execute(CommandContext commandContext) {
        HistoricProcessInstanceEntity hisProIns = null;
        if (procInstId != null) {
            hisProIns = CommandContextUtil.getHistoricProcessInstanceEntityManager(commandContext).findById(procInstId);
            if (hisProIns == null) {
                throw new FlowableObjectNotFoundException("HistoricProcessInstance " + procInstId + " doesn't exist", HistoricProcessInstanceEntity.class);
            }
        }
        CommentEntity comment = CommandContextUtil.getCommentEntityManager(commandContext).create();
        comment.setUserId(user);
        comment.setType((type == null) ? FlowableOperateEnum.Complete.name() : type);
        comment.setTime(CommandContextUtil.getProcessEngineConfiguration(commandContext).getClock().getCurrentTime());
        comment.setTaskId(taskId);
        comment.setProcessInstanceId(procInstId);
        comment.setAction(Event.ACTION_ADD_COMMENT);

        String eventMessage = StrUtil.isNotBlank(message) ? message.replaceAll("\\s+", " ") : "";
        if (eventMessage.length() > 3900) {
            eventMessage = eventMessage.substring(0, 3900) + "...";
        }
        comment.setMessage(eventMessage);
        comment.setFullMessage(message);
        CommandContextUtil.getCommentEntityManager(commandContext).insert(comment);
        return comment;
    }
}
